import { Byte } from '../../api/io/Byte';
import { OuterRewards } from './OuterRewards';
import { ITimer } from '../../api/timer/ITimer';
import { IAsync } from '../../api/event/IAsync';



/**用户额外信息属性枚举*/
export const enum E_UserExtra {
	/**用户外部领取的奖励*/
	OUTER_REWARDS = 0,
	/**枚举数量*/
	EnumCount = 1
}


/**用户额外信息*/
export class UserExtra {
	/**事件ID*/
	public static readonly EVENT_ID = 'STRUCT_DATA_USER_EXTRA_EVENT_ID';
	/**整体更新事件ID（部分只需要监听整体变化）*/
	public static readonly TOTAL_EVENT_ID = 'STRUCT_DATA_USER_EXTRA_TOTAL_EVENT_ID';
	/**缓存池*/
	private static POOL: UserExtra[] = [];

	/**创建入口*/
	public static create(json?: string): UserExtra {
		const c = this.POOL.pop() || new UserExtra();
		c._destroyed = false;
		c.resetProperty();
		if (json) {
			c.parse(json);
		}
		return c;
	}


	/**已释放*/
	protected _destroyed = false;
	/**用户外部领取的奖励*/
	protected _outerRewards: OuterRewards = null;


	/**构建函数-私有，防止外部创建*/
	private constructor() {
	}


	/**释放*/
	public destroy(): void {
		if (this._destroyed) {
			return;
		}
		this._destroyed = true;
		this.resetProperty(true);
		if (UserExtra.POOL.indexOf(this) === -1) {
			UserExtra.POOL.push(this);
		}
	}

	/**用户外部领取的奖励*/
	public get outerRewards() {
		return this._outerRewards;
	}



	/**通过枚举获取值*/
	public getV(k: E_UserExtra): any {
		switch (k) {
			case E_UserExtra.OUTER_REWARDS: return this._outerRewards;
			default: return null;
		}
	}


	/**通过枚举设置值*/
	public setV(k: E_UserExtra, v: any): void {
		switch (k) {
			case E_UserExtra.OUTER_REWARDS: this._outerRewards = v; break;
			default: break;
		}
	}


	/**初始化*/
	public resetProperty(fromDestroy = false): void {
		//用户外部领取的奖励
		if (this._outerRewards) {
			this._outerRewards.destroy();
			this._outerRewards = null;
		}
		if (!fromDestroy) {
			this._outerRewards = OuterRewards.create();
		}
	}


	/**序列化*/
	public stringify(toString: boolean): string | any {
		const json: any = {};
		if (this._outerRewards) {
			json.outerRewards = this._outerRewards.stringify(false);
		}

		return toString ? JSON.stringify(json) : json;
	}


	/**反序列化*/
	public parse(jsonv: string | any): this {
		this.resetProperty();
		if (!jsonv) {
			return this;
		}
		const json = typeof (jsonv) === 'string' ? JSON.parse(jsonv) : jsonv;
		if (json.outerRewards) {
			this._outerRewards.destroy();
			this._outerRewards = OuterRewards.create(json.outerRewards);
		}
		return this;
	}


	/**序列化-二进制*/
	public toBytes(byte: Byte): void {
		if (!byte) {
			return;
		}
		this._outerRewards.toBytes(byte);
	}


	/**反序列化-二进制*/
	public fromBytes(byte: Byte): this {
		this.resetProperty();
		if (!byte) {
			return;
		}
		this._outerRewards.fromBytes(byte);
		return this;
	}


	/**克隆*/
	public clone(): UserExtra {
		const byte = Byte.createFromPool();
		this.toBytes(byte);
		byte.pos = 0;
		const clonev = UserExtra.create().fromBytes(byte);
		Byte.recoverToPool(byte);
		return clonev;
	}


	/**处理更新*/
	public processUpdate(jsonv: string): void {
		if (!jsonv) {
			return;
		}

		const eventID = UserExtra.EVENT_ID;
		const us = JSON.parse(jsonv);

		for (let i = 0, len = us.length; i < len;) {
			const idx = us[i];
			//用户外部领取的奖励
			if (idx === E_UserExtra.OUTER_REWARDS) {
				const fui: string = us[i + 1];
				if (this._outerRewards) {
					this._outerRewards.processUpdate(fui);
				}
				else {
					console.error('UserExtra outerRewards is null when update.');
				}
				IAsync.dispatch(eventID, idx);
				i += 2;
				continue;
			}

			console.error('[Struct Data] can not find enum in UserExtra with idx = ' + idx + ', version maybe wrong.')
		}

		//全更事件
		ITimer.callLater(this, this.dispatchTotalUpdate);
	}


	/**比对不一致结果*/
	public getCompareInfo(other: UserExtra): string {
		if (!other) {
			return null;
		}

		const updates: any[] = [];

		//用户外部领取的奖励
		{
			const ui = this._outerRewards.getCompareInfo(other._outerRewards);
			if (ui && ui.length > 0) {
				updates.push(E_UserExtra.OUTER_REWARDS, ui);
			}
		}

		const jsonv = updates.length === 0 ? null : JSON.stringify(updates);
		return jsonv;
	}


	/**全部更新*/
	protected dispatchTotalUpdate(): void {
		IAsync.dispatch(UserExtra.TOTAL_EVENT_ID, this.getV(0));
	}

}
